//
//  VideoPlayerBaseControlLayer.swift
//  VideoPlayer
//
//  Created by JY_NEW on 2021/10/13.
//

import Foundation
import UIKit
import FXEvent
import UICreate

/// 自动取消激活图层，短时间内没有操作则自动隐藏
open class VideoPlayerAutoDeactiveLayer: VideoPlayerBaseLayer {
    private var _originalContainerView: UIView?
    private var _customContainerView = ContainerView()
    open override var containerView: UIView? {
        get {
            return _originalContainerView == nil ? nil : _customContainerView
        }
        set {
            if newValue !== _originalContainerView {
                _customContainerView.removeFromSuperview()
                if let view = newValue {
                    view.add(_customContainerView, layout: .margin)
                }
                if _originalContainerView == nil {
                    self.loadContainerView(_customContainerView)
                }
                _originalContainerView = newValue
            }
        }
    }
    /// 计时器
    public let timer = FXTimer(interval: 1)
    /// 自动关闭计时间隔，默认5秒
    open var autoDeactiveTimeInterval: TimeInterval { return 5 }
    
    public override init() {
        super.init()
        self.timer.addBlock { [weak self] in
            guard let self = self else { return }
            if self._customContainerView.timeIntervalSinceLastHit >= self.autoDeactiveTimeInterval {
                self.deactive()
            }
        }
    }
    
    open func willShow() {
        // 每次显示重新计时
        self._customContainerView.lastHitTime = Date()
        self.timer.start()
    }
    open func willHide() {
        // 每次关闭重置计时
        self._customContainerView.lastHitTime = nil
        self.timer.stop()
    }
}
extension VideoPlayerAutoDeactiveLayer {
    open class ContainerView: UIView {
        var lastHitTime: Date?
        open var timeIntervalSinceLastHit: TimeInterval {
            return -(self.lastHitTime?.timeIntervalSinceNow ?? 0)
        }
        // 每次点击重置计时
        open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
            let view = super.hitTest(point, with: event)
            if view == self {
                return nil
            }
            self.lastHitTime = Date()
            return view
        }
    }
}
